import { EExceptionStatusCode, IException } from '@/types/common'
import { ZodError } from 'zod'

// 格式化zod错误为数据
const formatZodErrorToData = (error: ZodError) => {
  const dataMap = new Map<string | number, string>()
  const { issues } = error
  // 遍历错误信息
  issues.forEach(issue => {
    const { path, message } = issue
    if (path.length > 0 && message) {
      path.forEach(field => {
        // 如果没有该字段的错误信息，则添加
        if (!dataMap.has(field)) {
          dataMap.set(field, message)
        }
      })
    }
  })
  // 转换为数组
  return Array.from(dataMap).map(([field, message]) => ({ field, message }))
}

// 请求超时 异常类
export default class RequestValidateError extends Error implements IException {
  // 状态码
  public statusCode: EExceptionStatusCode

  // 异常状态下携带的数据
  public data?: { field: string | number; message: string }[]

  // 构造函数
  constructor(error: ZodError, message: string = 'Request Validation Failed Error') {
    super(message)
    this.statusCode = EExceptionStatusCode.REQUEST_VALIDATE_FAILED
    this.name = 'FormValidateError'
    this.data = formatZodErrorToData(error)
  }
}
